如何用Numpy计算导数

您所在的位置:网站首页 python 偏导数 如何用Numpy计算导数

如何用Numpy计算导数

2024-07-10 17:48| 来源: 网络整理| 查看: 265

如何用Numpy计算导数

在这篇文章中,我们将学习如何使用NumPy计算导数。一般来说,NumPy没有提供任何强大的函数来计算不同多项式的导数。然而,NumPy可以使用函数numpy.poly1d()和div()来计算一维多项式的特殊情况。

需要使用的函数: poly1d()。它有助于定义一个多项式表达式或一个函数。 deriv()。计算并给我们提供导数表达式 步骤: 首先,我们需要使用numpy.poly1d()函数来定义一个多项式函数。 然后我们需要用derive()函数来推导导数表达式。 最后,我们可以把所需的值给x,以数值计算导数。

下面是一些例子,我们用NumPy计算一些表达式的导数。在这里,我们将变量 “var “中的表达式与 “x “进行微分。

示例 1:

import numpy as np    # defining polynomial function var = np.poly1d([1, 0, 1]) print("Polynomial function, f(x):\n", var)    # calculating the derivative derivative = var.deriv() print("Derivative, f(x)'=", derivative)    # calculates the derivative of after  # given value of x print("When x=5  f(x)'=", derivative(5))

输出:

如何用Numpy计算导数?

示例 2:

import numpy as np    # defining polynomial function var = np.poly1d([4, 9, 5, 1, 6]) print("Polynomial function, f(x):\n", var)    # calculating the derivative derivative = var.deriv() print("Derivative, f(x)'=\n", derivative)    # calculates the derivative of after  # given value of x print("When x=3  f(x)'=", derivative(3))

输出:

如何用Numpy计算导数?

示例 3:

import numpy as np    # defining polynomial function var = np.poly1d([5, 4, 9, 5, 1, 6]) print("Polynomial function:\n", var)    # calculating the derivative derivative = var.deriv() print("Derivative, f(x)'=\n", derivative)    # calculates the derivative of after  # given value of x print("When x=2  f(x)'=", derivative(0.2))

输出:

如何用Numpy计算导数?

为了计算双倍导数,我们可以简单地使用 deriv() 函数两次。

示例 4:

import numpy as np    # defining polynomial function var = np.poly1d([3, 5, 4, 9, 5, 1, 6]) print("Polynomial function:\n", var)    # calculating the derivative derivative = var.deriv() print("Derivative, f(x)'=\n", derivative)    # calculates the derivative of after  # given value of x print("When x=1  f(x)'=", derivative(1)) derivative1 = derivative.deriv()    print("\n\nDerivative, f(x)''=\n", derivative1) print("When x=1  f(x)'=", derivative1(1))

输出:

如何用Numpy计算导数?



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3